// pages/garage/garage.js
const app = getApp();
Page({
    /**
     * 组件的初始数据
     */
    data: {
      onReachBottomLoading: false,
      refreshed: false, // 将本属性设置为true，收起下拉刷新，可多次设置为true（即便原来已经是true了）
      userAgreement: true,
      StatusBar: app.globalData.StatusBar,
      CustomBar: app.globalData.CustomBar,
      screenHeight: app.globalData.screenHeight,
      modalName: null,
      searchParams:{
        pageNum: 1,
        pageSize: 6,
        status: '1',
        keyword:'',
        pages:'',
        total:''
      },
      nocar: true,
      carList:{},
      scopeCar:{},
      operationPageNum:0,
      closeReasonsList:['已经卖给消费者','批发给同行','收到定金了','不便透露'],
      closeReasons:'',
      haveSeeAuth: false,
      userInfo:{},
      topNum:0,
      cangotop: false,
      searchtype:null,
      dealerInfo:{}
    },

    /**
     * 组件的方法列表
     */
    
      // 获取海报。
      // getPoster(){
      //   this.showShareModal();
      // },
      
      showShareModal(){
        this.selectComponent('#posterComponent').showShareModal('');
        // app.sHttp.shareqrCode({pageUrl:'pages/card/card',scene:'cid='+car.carId}).then(res =>{
        //   let userQrcode = 'data:image/png;base64,' + res.base64;

        // },err=>{
        //   app.error(err.msg);
        // });
      },
      seeBids(){
        if (this.isHaveAuth('viewCar')) {
          let car = this.data.scopeCar;
          this.hideModal();
          wx.navigateTo({
            url: '/pages/garage/offerPrice/offerPrice?cid='+car.carId,
          })
        }else{
          app.error('您无权操作');
        }
      },
      // 降价一口价
      secondBatch(){
        if (this.isHaveAuth('manageSecondBatch')) {
          let car = this.data.scopeCar;
          app.globalData.atttionCar = car;
          this.hideModal();
          wx.navigateTo({
            url: '/pages/garage/secondBatch/secondBatch?cid=' + car.carId,
          })
        }else{
          app.error('您无权操作');
        }
      },
      // 重新上架
      reShelving(){
        app.sHttp.carManageModifyStatus({carId:this.data.scopeCar.carId,status:1}).then(res =>{
          this.hideModal();
          app.success('上架成功~');
          let self = this;
          setTimeout(() => {
            self.carManageList({pageNum:self.data.operationPageNum,pageSize:6,status:self.data.searchParams.status,keyword:self.data.searchParams.keyword});
          }, 1000);
        },err=>{
          app.error(err.msg);
        })
      },
      // 下架弹窗
      showOffTheShelf(e){
        if (this.isHaveAuth('closCar')) {
          if(this.getTabBar()){
            this.getTabBar().hideTabbar();
          }
          let car = e.currentTarget.dataset.car;
          if (car.status != 1) {
            this.setData({
              'scopeCar': car
            })
            this.showShareModal();
          }else{
            this.setData({
              'scopeCar': car,
              'operationPageNum': e.currentTarget.dataset.pagenum,
              'modalName': 'offTheShelf'
            });
          }
        }else{
          app.error('您无权操作');
        }
      },
      offTheShelf(){
        if("" == this.data.closeReasons){
          app.alert('请选择下架原因');
          return;
        }
        app.sHttp.carManageModifyStatus({carId:this.data.scopeCar.carId,status:2,closeReasons:this.data.closeReasons}).then(res =>{
          this.hideModal();
          app.success('下架成功~');
          let self = this;
          if(self.data.userAgreement){
            this.showShareModal();
          }
          setTimeout(() => {
            self.carManageList({pageNum:self.data.operationPageNum,pageSize:6,status:self.data.searchParams.status,keyword:self.data.searchParams.keyword});
          }, 1000);
        },err=>{
          app.error(err.msg);
        })
      },
      carManageDetail(){
        let car = this.data.scopeCar;
        this.hideModal();
        wx.navigateTo({
          url: '/pages/garage/carDetail/carDetail?cid=' + car.carId,
        })
      },
      // 跳转到车辆详情页面
      jumpToCardInfo(e){
        let cid = e.currentTarget.dataset.cid;
        wx.navigateTo({
          url: '/pages/card/card?cid=' + cid+'&self=selfCar',
        })
      },

      carManageList(searchParams){
        this.setData({
          'onReachBottomLoading': true
        })
        app.sHttp.carManageList(searchParams).then(res =>{
          if (searchParams.pageNum == 1 && res.result.carList.length == 0) {
            this.setData({
              'nocar': true,
              'onReachBottomLoading': false
            })
          }else{
            let carList = this.data.carList;
            res.result.carList.forEach(element => {
              if(element.insuranceReportType || element.mtnceReportType){
                element.haveReport = true;
              }else{
                element.haveReport = false;
              }
            });
            carList[searchParams.pageNum] = res.result.carList;
            this.setData({
              'carList': carList,
              'nocar': false,
              'searchParams.pages': res.result.pages,
              'searchParams.total': res.result.total,
              'onReachBottomLoading': false
            })
          }
        },err=>{
          app.error(err.msg);
        })
      },
      onReachBottom(){
        // 触底加载
        let searchParams = this.data.searchParams;
        if (searchParams.pageNum == searchParams.pages) {
          //app.alert('没有更多了哦~');
        }else{
          searchParams.pageNum = searchParams.pageNum+1;
          this.setData({
            'searchParams': searchParams
          });
          this.carManageList(searchParams);
        }
      },
      bindtapInput(e){
        this.setData({
          'searchParams.keyword': e.detail.value
        })
      },
      clearQuery(){
        this.setData({
          'searchParams.keyword': '',
          'searchtype': 0
        });
        this.goQuery();
      },
      switchType(e){
          let type = e.currentTarget.dataset.type;
          let _this = this;
          this.setData({
              'searchParams.status': type
          },(res)=>{
              _this.clearQuery();
          })
      },
      doNothing(){},
      loveHerByOneDay(her){
        if(Object.keys(her).length != 0){
          // 保留里面的 key 为 1 的数据
          let newObj = {};
          newObj[1] = her[1];
          return newObj;
        }else{
          return {};
        }
      },
      goQuery(e){
        let self = this;
        if(undefined  != e && this.data.searchtype != 1){
          if(this.data.searchParams.keyword == ''){
            return;
          }
        }
        let searchtype = undefined ==  e?0:e.currentTarget.dataset.searchtype
        this.setData({
          'searchParams.pageNum':1,
          'searchParams.total':'',
          'searchParams.pages':'',
          'carList': self.loveHerByOneDay(self.data.carList),
          'searchtype': searchtype
        });
        this.carManageList(this.data.searchParams);
      },
      carManageClearCar(e){
        let pageNum = e.currentTarget.dataset.pagenum;
        let index = e.currentTarget.dataset.idx;
        let carId = e.detail;
        if (0 == carId) {
          app.error('请关闭重试');
          return;
        };
        app.sHttp.carManageClearCar(carId).then(res =>{
          let carList = this.data.carList;
          carList[pageNum][index].clearScore = 100;
          carList[pageNum][index].todayIsClear = 1;
          this.setData({
            'carList':carList
          });
          // 重播动画
          this.selectComponent('#barpie'+carId).reloadAnimation();
          // this.goQuery();
        },err=>{
          app.error(err.msg);
        })
      },
      showModal(e) {
        if(this.getTabBar()){
          this.getTabBar().hideTabbar();
        }
          this.setData({
            modalName: e.currentTarget.dataset.target
          });
      },
      hideModal(e) {
        if(this.getTabBar()){
          this.getTabBar().showTabbar();
        }
          this.setData({
            modalName: null
          });
      },
      // 管理车辆
      manageCar(e){
        if (this.isHaveAuth('editCar')) {
          if(this.getTabBar()){
            this.getTabBar().hideTabbar();
          }
          this.setData({
            'scopeCar': e.currentTarget.dataset.car,
            'operationPageNum': e.currentTarget.dataset.pagenum,
            'modalName': 'manageCar'
          });
        }else{
          app.error('您无权操作');
        }
      },
      useUserAgreement(){
        this.setData({
          userAgreement: !this.data.userAgreement
        })
      },
      chooseReasons(e){
        this.setData({
          'closeReasons': e.currentTarget.dataset.content
        })
      },
      isHaveAuth(authIcon){
        let index = this.data.roleList.indexOf(authIcon);
        return index != -1?true:false;
      },
      onPageScroll(e){
        let cangotop = false;
        if (e.scrollTop > 100) {
          cangotop = true;
        }
        if(cangotop != this.data.cangotop){
          this.setData({
            cangotop: cangotop
          })
        }
      },
      //回到顶部
      goTop: function (e) {  // 一键回到顶部
        wx.pageScrollTo({
          scrollTop: 0
        })
      },
      pullDownRefresh(){
        this.lifeInit();
        let self = this;
        setTimeout(() => {
          self.setData({
            'refreshed': true
          })
        }, 1000);
      },
      // 真正的初始化页面。
      lifeInit(){
        // 加载一个方法。来装载Token以及其他参数。
        this.InitUserStatus();
        app.globalData.garageComponentLoadTime = new Date();
      },
      async InitUserStatus(){
        await app.checkToken();
        let accountStatus = app.accountStatus;
        // 回填权限列表。
        let userInfo = app.globalData.userInfo;
        if (undefined != userInfo.roleList && null != userInfo.roleList) {
          this.setData({
            roleList: userInfo.roleList
          });
        }
        this.setData({
          accountStatus: accountStatus,
          userInfo:userInfo
        });
        if(this.getTabBar()){
          this.getTabBar().setData({
            roleList:userInfo.roleList,
            accountStatus:accountStatus,
            userInfo:userInfo,
            remindList:userInfo.remindList
          })
        }
        this.loadDealerInfo();
        this.loadMsgUnreadStat();
        this.InitUserAuth();
      },
      loadMsgUnreadStat(){
        app.sHttp.msgUnreadStat().then(res =>{
          this.setData({
            'msgNumber': res.result
          });
          if(this.getTabBar()){
            this.getTabBar().setData({
              'msgNumber': res.result
            })
          }
        },err=>{
        })
      },  // 加载下车商的信息。
      loadDealerInfo(){
        if(Object.keys(app.globalData.dealerInfo).length === 0){
          app.sHttp.dealerInfo().then(res =>{
            if(res.result.city == '市辖区'){
              res.result.city = res.result.province;
            }
            app.globalData.dealerRegion = [res.result.province, res.result.city , res.result.district];
            app.globalData.dealerInfo = res.result;
            // 并且把地址填充到
            // app.globalData.defaultCity = res.result.city || '全国';
            this.setData({
              'dealerInfo': app.globalData.dealerInfo
            })
          },err=>{
          })
        }else{
          this.setData({
            'dealerInfo': app.globalData.dealerInfo
          })
        }
      },
      InitUserAuth(){
        let userInfo = app.globalData.userInfo;
        this.setData({
          'userInfo': userInfo
        })
        if (undefined != userInfo.roleList && null !=userInfo.roleList) {
          let index = userInfo.roleList.indexOf('viewCar');
          if (index != -1) {
            this.setData({
              'haveSeeAuth': true,
              'roleList': userInfo.roleList
            });
            this.goQuery();
          }
        }
      },
      onShow() {
        // 是否需要请求
        if(null == app.globalData.garageComponentLoadTime || app.needReload(app.globalData.garageComponentLoadTime)){
          this.lifeInit();
        }
        if (typeof this.getTabBar === 'function' && this.getTabBar()) {
          this.getTabBar().setData({
            selected: 3
          })
        }
      }
})
